package com.punai.assetlibrary.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.punai.assetlibrary.entiry.dtos.SrQdZckDto;
import com.punai.assetlibrary.service.SrQdZckService;
import com.punai.common.core.controller.BaseController;
import com.punai.common.core.domain.AjaxResult;
import com.punai.common.core.page.TableDataInfo;
import com.punai.common.utils.StringUtil;
import com.punai.dataclean.domain.IncomeDataCleanInfo;
import com.punai.evaluationSystem.incomeDataEvalute.domain.EvaluationDataPriceSr;
import com.punai.evaluationSystem.incomeDataEvalute.domain.EvaluationResultsSr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/assetslibrary/bqitemzck")
public class SrQdZckController extends BaseController {

    @Autowired
    private SrQdZckService srQdZckService;


    @PostMapping("/initTableData")
    public TableDataInfo initTableData(@RequestBody SrQdZckDto form) {
        form.setPtype("2");
        String[] dateRange = form.getDateRange();
        if (dateRange != null && dateRange.length >= 2) {
            if (StringUtil.isNotNullOrEmpty(dateRange[0])) {
                form.setTimeStart(dateRange[0]);
            }

            if (StringUtil.isNotNullOrEmpty(dateRange[1])) {
                form.setTimeEnd(dateRange[1]);
            }
        }

        if ("全部".equals(form.getProjectDept())) {
            form.setProjectDept(null);
        }

        String address = StrUtil.join("", form.getAddressList());
        if ("全部".equals(address)) {
            form.setAddress(null);
        } else {
            form.setAddress(address);
        }
        
        if ("全部".equals(form.getPjjgsj())) {
            form.setPjjgsj(null);
        }
        List<EvaluationDataPriceSr> data = srQdZckService.initTableData(form);
        if (data == null) {
            return new TableDataInfo();
        }
        return getDataTable(data);
    }

    @PostMapping("/initShowDetailTable")
    public TableDataInfo initShowDetailTable(@RequestBody SrQdZckDto form) {
        form.setPtype("4");
        String[] dateRange = form.getDateRange();
        if (dateRange != null && dateRange.length >= 2) {
            if (StringUtil.isNotNullOrEmpty(dateRange[0])) {
                form.setTimeStart(dateRange[0]);
            }

            if (StringUtil.isNotNullOrEmpty(dateRange[1])) {
                form.setTimeEnd(dateRange[1]);
            }
        }

        if ("全部".equals(form.getProjectDept())) {
            form.setProjectDept(null);
        }
        
        String address = StrUtil.join("", form.getAddressList());
        if ("全部".equals(address)) {
            form.setAddress(null);
        } else {
            form.setAddress(address);
        }
        
        if ("全部".equals(form.getPjjgsj())) {
            form.setPjjgsj(null);
        }

        
        List<EvaluationDataPriceSr> data = srQdZckService.initTableData(form);
        if (CollUtil.isNotEmpty(data)) {
            for (EvaluationDataPriceSr priceSr : data) {
                Map<String, Object> priceRange = srQdZckService.findByPriceRangMaxAndMin(priceSr);
                System.out.println(priceRange);
                Object min = priceRange.get("min");
                Object max = priceRange.get("max");
                StringBuilder builder = new StringBuilder();
                if (min != null) {
                    builder.append(min).append("-");
                }

                if (max != null) {
                    builder.append(max);
                }

                priceSr.setPriceRange(builder.toString());
            }
        }
        if (data == null) {
            return new TableDataInfo();
        }
        return getDataTable(data);
    }

    @PostMapping("/main1")
    public AjaxResult main1(@RequestBody SrQdZckDto form) {
        String[] dateRange = form.getDateRange();
        if (dateRange != null && dateRange.length >= 2) {
            if (StringUtil.isNotNullOrEmpty(dateRange[0])) {
                form.setTimeStart(dateRange[0]);
            }

            if (StringUtil.isNotNullOrEmpty(dateRange[1])) {
                form.setTimeEnd(dateRange[1]);
            }
        }

        if ("全部".equals(form.getProjectDept())) {
            form.setProjectDept(null);
        }

        String address = StrUtil.join("", form.getAddressList());
        if ("全部".equals(address)) {
            form.setAddress(null);
        } else {
            form.setAddress(address);
        }
        
        if ("全部".equals(form.getPjjgsj())) {
            form.setPjjgsj(null);
        }
        List<EvaluationDataPriceSr> imageData = srQdZckService.getImageData(BeanUtil.beanToMap(form));

        Map<String, List<EvaluationDataPriceSr>> collect = Optional.ofNullable(imageData)
                .map(List::stream)
                .orElseGet(Stream::empty)
                .collect(Collectors.groupingBy(EvaluationDataPriceSr::getPjjgsj, Collectors.toList()));

        List<String> x = new ArrayList<>();
        List<String> y = new ArrayList<>();
        Set<String> keySet = collect.keySet();
        for (String key : keySet) {
            x.add(key);
            List<EvaluationDataPriceSr> priceSrList = collect.get(key);
            BigDecimal sum = BigDecimal.ZERO;
            if (CollUtil.isNotEmpty(priceSrList)) {
                for (EvaluationDataPriceSr priceSr : priceSrList) {
                    BigDecimal userPrice = priceSr.getUserPrice();
                    Integer jgsl = priceSr.getJgsl();
                    if (userPrice != null && jgsl != null) {
                        sum = sum.add(userPrice.multiply(BigDecimal.valueOf(jgsl)));
                    }
                }
            }
            y.add(sum.toPlainString());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("labels", x);
        map.put("values", y);

        return AjaxResult.success(map);
    }

    @PostMapping("/main2")
    public AjaxResult main2(@RequestBody SrQdZckDto form) {
        String[] dateRange = form.getDateRange();
        if (dateRange != null && dateRange.length >= 2) {
            if (StringUtil.isNotNullOrEmpty(dateRange[0])) {
                form.setTimeStart(dateRange[0]);
            }

            if (StringUtil.isNotNullOrEmpty(dateRange[1])) {
                form.setTimeEnd(dateRange[1]);
            }
        }

        if ("全部".equals(form.getProjectDept())) {
            form.setProjectDept(null);
        }

        String address = StrUtil.join("", form.getAddressList());
        if ("全部".equals(address)) {
            form.setAddress(null);
        } else {
            form.setAddress(address);
        }
        
        if ("全部".equals(form.getPjjgsj())) {
            form.setPjjgsj(null);
        }
        List<EvaluationDataPriceSr> imageData = srQdZckService.getImageData(BeanUtil.beanToMap(form));

        Map<String, List<EvaluationDataPriceSr>> collect = imageData.stream().collect(Collectors.groupingBy(EvaluationDataPriceSr::getPjjgsj, Collectors.toList()));

        List<IncomeDataCleanInfo> zhdj = srQdZckService.calcZHDJ(collect, imageData);

        Map<String, List<IncomeDataCleanInfo>> listMap = Optional.ofNullable(zhdj)
                .map(List::stream)
                .orElseGet(Stream::empty)
                .collect(Collectors.groupingBy(IncomeDataCleanInfo::getPjjgsj, Collectors.toList()));

        List<String> x = new ArrayList<>();
        List<Map<String, Object>> y = new ArrayList<>();
        for (Map.Entry<String, List<IncomeDataCleanInfo>> entry : listMap.entrySet()) {
            x.add(entry.getKey());
        }

        Map<String, List<IncomeDataCleanInfo>> gs = Optional.ofNullable(zhdj)
                .map(List::stream)
                .orElseGet(Stream::empty)
                .filter(e -> e.getCompany() != null)
                .collect(Collectors.groupingBy(IncomeDataCleanInfo::getCompany, Collectors.toList()));

        Map<String, Object> result = new HashMap<>();
        result.put("labels", x);
        result.put("values", y);

        for (Map.Entry<String, List<IncomeDataCleanInfo>> entry : gs.entrySet()) {
            Map<String, Object> m = new HashMap<>();
            m.put("name", entry.getKey());
            m.put("type", "line");
            ArrayList<String> d = new ArrayList<>();
            for (String s : x) {
                Map<String, List<IncomeDataCleanInfo>> map2 = entry.getValue().stream().collect(Collectors.groupingBy(IncomeDataCleanInfo::getPjjgsj, Collectors.toList()));
                List<IncomeDataCleanInfo> infoList = map2.get(s);
                if (CollUtil.isNotEmpty(infoList)) {
                    String sum = infoList.stream().map(IncomeDataCleanInfo::getPrice).filter(item -> item != null).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(3, BigDecimal.ROUND_HALF_UP).toPlainString();
                    d.add(sum);
                } else {
                    d.add("-");
                }
            }

            m.put("data", d);
            y.add(m);
        }

        return AjaxResult.success(result);
    }

    @PostMapping("/main3")
    public AjaxResult main3(@RequestBody SrQdZckDto form) {
        String[] dateRange = form.getDateRange();
        if (dateRange != null && dateRange.length >= 2) {
            if (StringUtil.isNotNullOrEmpty(dateRange[0])) {
                form.setTimeStart(dateRange[0]);
            }

            if (StringUtil.isNotNullOrEmpty(dateRange[1])) {
                form.setTimeEnd(dateRange[1]);
            }
        }

        if ("全部".equals(form.getProjectDept())) {
            form.setProjectDept(null);
        }

        String address = StrUtil.join("", form.getAddressList());
        if ("全部".equals(address)) {
            form.setAddress(null);
        } else {
            form.setAddress(address);
        }
        
        if ("全部".equals(form.getPjjgsj())) {
            form.setPjjgsj(null);
        }
        List<EvaluationDataPriceSr> imageData = srQdZckService.getImageData(BeanUtil.beanToMap(form));

        Map<String, List<EvaluationDataPriceSr>> collect = imageData.stream().collect(Collectors.groupingBy(EvaluationDataPriceSr::getPjjgsj, Collectors.toList()));

        List<IncomeDataCleanInfo> zhdj = srQdZckService.calcZHDJ(collect, imageData);

        Map<String, List<IncomeDataCleanInfo>> listMap = Optional.ofNullable(zhdj)
                .map(List::stream)
                .orElseGet(Stream::empty)
                .collect(Collectors.groupingBy(IncomeDataCleanInfo::getPjjgsj, Collectors.toList()));

        List<String> x = new ArrayList<>();
        List<Map<String, Object>> y = new ArrayList<>();
        for (Map.Entry<String, List<IncomeDataCleanInfo>> entry : listMap.entrySet()) {
            x.add(entry.getKey());
        }

        Map<String, List<IncomeDataCleanInfo>> gs = Optional.ofNullable(zhdj)
                .map(List::stream)
                .orElseGet(Stream::empty)
                .filter(e -> e.getAddress() != null)
                .collect(Collectors.groupingBy(IncomeDataCleanInfo::getAddress, Collectors.toList()));

        Map<String, Object> result = new HashMap<>();
        result.put("labels", x);
        result.put("values", y);

        for (Map.Entry<String, List<IncomeDataCleanInfo>> entry : gs.entrySet()) {
            Map<String, Object> m = new HashMap<>();
            m.put("name", entry.getKey());
            m.put("type", "line");
            ArrayList<String> d = new ArrayList<>();
            for (String s : x) {
                Map<String, List<IncomeDataCleanInfo>> map2 = entry.getValue().stream().collect(Collectors.groupingBy(IncomeDataCleanInfo::getPjjgsj, Collectors.toList()));
                List<IncomeDataCleanInfo> infoList = map2.get(s);
                if (CollUtil.isNotEmpty(infoList)) {
                    String sum = infoList.stream().filter(v -> v.getPrice() != null).map(IncomeDataCleanInfo::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(3, BigDecimal.ROUND_HALF_UP).toPlainString();
                    d.add(sum);
                } else {
                    d.add("-");
                }
            }

            m.put("data", d);
            y.add(m);
        }

        return AjaxResult.success(result);
    }

    @GetMapping("/initTabTableHeader/{code}")
    public AjaxResult initTabTableHtml(@PathVariable("code") String code) {
        Set<String> tableHead =  srQdZckService.getHeadData(code, "02");
        return AjaxResult.success(tableHead);
    }

    @PostMapping("/initShowTableData")
    public AjaxResult initShowTableData(@RequestBody SrQdZckDto form) {
        String[] dateRange = form.getDateRange();
        if (dateRange != null && dateRange.length >= 2) {
            if (StringUtil.isNotNullOrEmpty(dateRange[0])) {
                form.setTimeStart(dateRange[0]);
            }

            if (StringUtil.isNotNullOrEmpty(dateRange[1])) {
                form.setTimeEnd(dateRange[1]);
            }
        }

        if ("全部".equals(form.getProjectDept())) {
            form.setProjectDept(null);
        }

        String address = StrUtil.join("", form.getAddressList());
        if ("全部".equals(address)) {
            form.setAddress(null);
        } else {
            form.setAddress(address);
        }
        
        if ("全部".equals(form.getPjjgsj())) {
            form.setPjjgsj(null);
        }
        String type = form.getType();
        if ("2".equals(type)) {
//            form.setProjectDept("");
            List<EvaluationDataPriceSr> imageData = srQdZckService.getImageData(BeanUtil.beanToMap(form));
            Map<String, List<EvaluationDataPriceSr>> listMap = imageData.stream().collect(Collectors.groupingBy(EvaluationDataPriceSr::getPjjgsj, Collectors.toList()));
            List<IncomeDataCleanInfo> calcLRE = srQdZckService.calcZHDJ(listMap, imageData);

            Map<String, List<IncomeDataCleanInfo>> gs = calcLRE.stream().filter(e -> e.getAddress() != null).collect(Collectors.groupingBy(IncomeDataCleanInfo::getAddress, Collectors.toList()));

            ArrayList<Map<String, Object>> r = new ArrayList<>();

            for (Map.Entry<String, List<IncomeDataCleanInfo>> entry : gs.entrySet()) {
                Map<String, Object> result = new HashMap<>();
                String key = entry.getKey();
                result.put("name", key);
                List<IncomeDataCleanInfo> value = entry.getValue();
                Map<String, List<IncomeDataCleanInfo>> map = value.stream().collect(Collectors.groupingBy(IncomeDataCleanInfo::getPjjgsj));
                Set<Map.Entry<String, List<IncomeDataCleanInfo>>> mapEntry = map.entrySet();
                for (Map.Entry<String, List<IncomeDataCleanInfo>> listEntry : mapEntry) {
                    List<IncomeDataCleanInfo> infoList = listEntry.getValue();
                    if (CollUtil.isNotEmpty(infoList)) {
                        String data = infoList.stream().map(IncomeDataCleanInfo::getPrice).filter(item -> item != null).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(3, BigDecimal.ROUND_HALF_UP).toPlainString();
                        result.put(listEntry.getKey(), data);
                    }
                }
                r.add(result);
            }
            return AjaxResult.success(r);
        } else {
//            form.setAddress("");
            List<EvaluationDataPriceSr> imageData = srQdZckService.getImageData(BeanUtil.beanToMap(form));

            Map<String, List<EvaluationDataPriceSr>> listMap = imageData.stream().collect(Collectors.groupingBy(EvaluationDataPriceSr::getPjjgsj, Collectors.toList()));

            List<IncomeDataCleanInfo> calcLRE = srQdZckService.calcZHDJ(listMap, imageData);

            Map<String, List<IncomeDataCleanInfo>> gs = calcLRE.stream().filter(e -> e.getCompany() != null).collect(Collectors.groupingBy(IncomeDataCleanInfo::getCompany, Collectors.toList()));

            List<Map<String, Object>> y = new ArrayList<>();

            for (Map.Entry<String, List<IncomeDataCleanInfo>> entry : gs.entrySet()) {
                Map<String, Object> result = new HashMap<>();
                String key = entry.getKey();
                result.put("name", key);
                List<IncomeDataCleanInfo> value = entry.getValue();
                Map<String, List<IncomeDataCleanInfo>> map = value.stream().collect(Collectors.groupingBy(IncomeDataCleanInfo::getPjjgsj));
                Set<Map.Entry<String, List<IncomeDataCleanInfo>>> mapEntry = map.entrySet();
                for (Map.Entry<String, List<IncomeDataCleanInfo>> listEntry : mapEntry) {
                    List<IncomeDataCleanInfo> infoList = listEntry.getValue();
                    if (CollUtil.isNotEmpty(infoList)) {
                        String data = infoList.stream().map(IncomeDataCleanInfo::getPrice).filter(item -> item != null).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(3, BigDecimal.ROUND_HALF_UP).toPlainString();
                        result.put(listEntry.getKey(), data);
                    }
                }
                y.add(result);
            }

            return AjaxResult.success(y);
        }
    }



    @PostMapping("/getQc")
    public AjaxResult getQc(@RequestBody SrQdZckDto form) {
        form.setEvalType("02");
        List<EvaluationResultsSr> result = srQdZckService.getQc(form);
        return AjaxResult.success(result);
    }

}
